package com.android.equipment.ui.people

import android.os.Bundle
import android.view.View
import com.android.equipment.R
import com.android.equipment.base.BaseActivity
import com.android.equipment.dao.People
import com.android.equipment.dao.operate.DaoPeople
import com.android.equipment.databinding.ActivityEditPeopleBinding
import com.android.equipment.utils.GlideEngine
import com.android.equipment.utils.ToastUtil
import com.blankj.utilcode.util.ImageUtils
import com.blankj.utilcode.util.SDCardUtils
import com.blankj.utilcode.util.StringUtils
import com.gyf.immersionbar.ImmersionBar
import com.hjq.bar.OnTitleBarListener
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.engine.CompressFileEngine
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.utils.DateUtils
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import top.zibin.luban.OnNewCompressListener
import java.io.File


class EditPeopleActivity : BaseActivity<ActivityEditPeopleBinding>() {
    private var sexType = 0
    lateinit var currentPeople: People
    private var isEdit = false
    private var id: Long = 0
    override fun setLayoutContent(): ActivityEditPeopleBinding {
        return ActivityEditPeopleBinding.inflate(layoutInflater)
    }

    @Throws(Exception::class)
    override fun initView(savedInstanceState: Bundle?) {
        id = intent.getLongExtra("id", 0L)
        isEdit = id > 0L
    }

    override fun initData() {
        if (isEdit) { // 修改
            binding.mTitleBar.setTitle("人员修改")
            binding.tvSubmit.text = "确认修改"
            val people = DaoPeople.getInstance().getPeople(id)
            currentPeople = people
            setPeopleInfo()
        } else { // 新增
            binding.mTitleBar.setTitle("人员新增")
            binding.tvSubmit.text = "确认新增"
            currentPeople = People()
        }
    }

    override fun initEvent() {
        super.initEvent()
        binding.mTitleBar.setOnTitleBarListener(object : OnTitleBarListener{
            override fun onLeftClick(v: View?) {
               mSwipeBackHelper.backward()
            }

            override fun onTitleClick(v: View?) {
                TODO("Not yet implemented")
            }

            override fun onRightClick(v: View?) {
                TODO("Not yet implemented")
            }

        })
        binding.llMan.setOnClickListener { v: View? ->
            if (sexType == 1) {
                return@setOnClickListener
            }
            sexType = 1
            sexChange()
        }

        binding.llWoman.setOnClickListener { v: View? ->
            if (sexType == 0) {
                return@setOnClickListener
            }
            sexType = 0
            sexChange()
        }

        binding.ivPhoto.setOnClickListener { v: View? ->
            if (binding.ivDelete.visibility == View.GONE) {
                PictureSelector.create(this)
                    .openGallery(SelectMimeType.ofImage())
                    .setImageEngine(GlideEngine.createGlideEngine())
                    .setMaxSelectNum(1)
                    .setCompressEngine(CompressFileEngine { context, source, call ->
                        Luban.with(context).load(source).ignoreBy(100)
                            .setCompressListener(object :OnNewCompressListener {
                                override fun onStart() {
                                }

                                override fun onSuccess(source: String?, compressFile: File?) {
                                    call.onCallback(source, compressFile?.absolutePath);
                                }

                                override fun onError(source: String?, p1: Throwable?) {
                                    call.onCallback(source, null);
                                }


                            }).launch()

                    })
                    .forResult(object : OnResultCallbackListener<LocalMedia?> {
                        override fun onResult(result: ArrayList<LocalMedia?>?) {
                            val path = result?.get(0)?.compressPath
                            if (!StringUtils.isEmpty(path)) {
                                val bitmap = ImageUtils.getBitmap(path)
                                binding.ivPhoto.setImageBitmap(bitmap)
                                currentPeople.peoplePhoto = path
                                binding.ivDelete.visibility = View.VISIBLE
                            }
                        }

                        override fun onCancel() {
                        }
                    })
            }
        }

        binding.ivDelete.setOnClickListener { v: View ->
            binding.ivPhoto.setImageResource(R.mipmap.icon_take_photo)
            currentPeople.peoplePhoto = ""
            v.visibility = View.GONE
        }

        binding.tvSubmit.setOnClickListener { v: View? ->
            if (checkCurrentPeople()) {
                if (isEdit) {
                    currentPeople.updateTime =
                        DateUtils.getYearDataFormat(System.currentTimeMillis())
                    DaoPeople.getInstance().updatePeople(currentPeople)
                    mSwipeBackHelper.backward()
                } else {
                    currentPeople.addTime =
                        DateUtils.getYearDataFormat(System.currentTimeMillis())
                    DaoPeople.getInstance().addPeople(currentPeople)
                    mSwipeBackHelper.backward()
                }
            }
        }
    }

    private fun checkCurrentPeople(): Boolean {
        if (StringUtils.isEmpty(binding.etName.text.toString())) {
            ToastUtil.showToastSafe("请输入姓名")
            return false
        }

        if (StringUtils.isEmpty(binding.etAge.text.toString())) {
            ToastUtil.showToastSafe("请输入年龄")
            return false
        }

        if (StringUtils.isEmpty(binding.etPhone.text.toString())) {
            ToastUtil.showToastSafe("请输入手机号")
            return false
        }

        val peoplePhoto = currentPeople.peoplePhoto
        if (StringUtils.isEmpty(peoplePhoto)) {
            ToastUtil.showToastSafe("请选择头像")
            return false
        }

        currentPeople.peopleAge = binding.etAge.text.toString()
        currentPeople.peopleName = binding.etName.text.toString()
        currentPeople.peopleSex = sexType
        currentPeople.peoplePhone = binding.etPhone.text.toString()

        return true
    }

    private fun setPeopleInfo() {
        binding.etName.setText(currentPeople.peopleName)
        binding.etAge.setText(currentPeople.peopleAge)
        binding.etPhone.setText(currentPeople.peoplePhone)
        sexType = currentPeople.peopleSex
        sexChange()
        val path = currentPeople.peoplePhoto
        val bitmap = ImageUtils.getBitmap(path)
        binding.ivPhoto.setImageBitmap(bitmap)
        binding.ivDelete.visibility = View.VISIBLE
    }


    private fun sexChange() {
        if (sexType == 1) {
            binding.ivMan.setImageResource(R.mipmap.icon_circle_sel)
            binding.ivWoman.setImageResource(R.mipmap.icon_circle_nor)
        } else {
            binding.ivMan.setImageResource(R.mipmap.icon_circle_nor)
            binding.ivWoman.setImageResource(R.mipmap.icon_circle_sel)
        }
    }

    override fun setStatusBar() {
        super.setStatusBar()
        ImmersionBar.with(this)
            .fullScreen(true)
            .statusBarColor(R.color.white)
            .statusBarDarkFont(true)
            .titleBar(binding.mTitleBar)
            .init()
    }
}
